﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using Renci.SshNet;
using Renci.SshNet.Sftp;


namespace Lemonc.Tools
{
    /// <summary>
    /// SFTP操作类
    /// </summary>
    public class SFTPHelper
    {
        #region 字段或属性
        private SftpClient sftp;
        /// <summary>
        /// SFTP连接状态
        /// </summary>
        public bool Connected { get { return sftp.IsConnected; } }
        #endregion

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="user">用户名</param>
        /// <param name="pwd">密码</param>
        public SFTPHelper(string host, string user, string pwd)
        {
            string[] arr = host.Split(':');
            string ip = arr[0];
            int port = 22;
            if (arr.Length > 1)
                port = Int32.Parse(arr[1]);
            sftp = new SftpClient(ip, port, user, pwd);
        }
        #endregion

        #region 连接SFTP
        /// <summary>
        /// 连接SFTP
        /// </summary>
        /// <returns>true成功</returns>
        public bool Connect()
        {
            try
            {
                if (!Connected)
                {
                    sftp.Connect();
                }
                return true;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("连接SFTP失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("连接SFTP失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        #region 断开SFTP
        /// <summary>
        /// 断开SFTP
        /// </summary> 
        public void Disconnect()
        {
            try
            {
                if (sftp != null && Connected)
                {
                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("断开SFTP失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("断开SFTP失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        #region SFTP上传文件
        /// <summary>
        /// SFTP上传文件
        /// </summary>
        /// <param name="localPath">本地路径</param>
        /// <param name="remotePath">远程路径</param>
        public void Put(string localPath, string remotePath)
        {
            try
            {
                if (Connected)
                {
                    using (var file = File.OpenRead(localPath))
                    {
                        sftp.UploadFile(file, remotePath + ".temp");
                        if (sftp.Exists(remotePath))
                        {
                            sftp.Delete(remotePath);
                        }
                        sftp.RenameFile(remotePath + ".temp", remotePath);
                    }
                }
                else
                {
                    throw new Exception(string.Format("SFTP文件上传失败，原因：{0}", "SFTP未连接"));
                }
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件上传失败，原因：{0}", ex.Message));
                sftp.Delete(remotePath + ".temp");
                throw new Exception(string.Format("SFTP文件上传失败，原因：{0}", ex.ToString()));
            }
        }
        #endregion

        #region SFTP获取文件
        /// <summary>
        /// SFTP获取文件
        /// </summary>
        /// <param name="remotePath">远程路径</param>
        /// <param name="localPath">本地路径</param>
        public bool Get(string remotePath, string localPath)
        {
            try
            {
                if (Connected)
                {
                    var byt = sftp.ReadAllBytes(remotePath);
                    File.WriteAllBytes(localPath + ".temp", byt);
                    FileInfo fitemp = new FileInfo(localPath + ".temp");
                    FileInfo fi = new FileInfo(localPath);
                    if (fi.Exists)
                    {
                        fi.Delete();
                    }
                    fitemp.MoveTo(localPath);
                    return true;
                }
                else
                {
                    throw new Exception(string.Format("SFTP文件下载失败，原因：{0}", "SFTP未连接"));
                }


            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
                throw new Exception(string.Format(remotePath+"文件获取失败，原因：{0}", ex.Message));
            }

        }
        #endregion

        #region 删除SFTP文件
        /// <summary>
        /// 删除SFTP文件 
        /// </summary>
        /// <param name="remoteFile">远程路径</param>
        public bool Delete(string remoteFile)
        {
            try
            {
                sftp.Delete(remoteFile);
                return true;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
                return false;
                //throw new Exception(string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
            }
        }
        #endregion

        #region 获取SFTP文件列表
        /// <summary>
        /// 获取SFTP文件列表
        /// </summary>
        /// <param name="remotePath">远程目录</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <returns></returns>
        public List<SftpFile> GetFileList(string remotePath, string fileSuffix)
        {
            try
            {
                if (Connected)
                {
                    var files = sftp.ListDirectory(remotePath);
                    var objList = new List<SftpFile>();
                    foreach (var file in files)
                    {
                        if (file.IsDirectory && file.Name.Replace(".", "") != "")
                        {
                            continue;
                        }
                        else
                        {
                            Regex r = new Regex(fileSuffix);
                            Match m = r.Match(file.Name);
                            if (m.Success)
                            {
                                objList.Add(file);
                            }
                            else { continue; }
                        }
                    }
                    return objList;
                }
                else
                {
                    throw new Exception(string.Format("SFTP文件下载失败，原因：{0}", "SFTP未连接"));
                }
                ;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="remotePath"></param>
        /// <param name="pathSuffix">4401\d*/SREPMSG/</param>
        /// <param name="fileSuffix">SRep4401\d{8}[2,3]{1}\d*\d.xml</param>
        /// <returns></returns>
        public void GetFileList(string remotePath, string pathSuffix, string fileSuffix, ref List<SftpFile> objList)
        {
            try
            {
                if (Connected)
                {
                    var files = sftp.ListDirectory(remotePath);
                    foreach (var file in files)
                    {
                        ArrayList directoryPaths = new ArrayList(pathSuffix.Split('/'));

                        if (file.IsDirectory && pathSuffix != "")
                        {
                            Regex r = new Regex(directoryPaths[0].ToString());
                            Match m = r.Match(file.Name);
                            if (m.Success)
                            {
                                directoryPaths.RemoveAt(0);
                                string str = string.Join(",", (string[])directoryPaths.ToArray(typeof(string)));
                                GetFileList(remotePath + file.Name + "/", str, fileSuffix, ref objList);
                            }
                            else
                            {
                                continue;
                            }

                        }
                        else if (pathSuffix == "")
                        {
                            Regex r = new Regex(fileSuffix);
                            Match m = r.Match(file.Name);
                            if (m.Success)
                            { objList.Add(file); }
                            else { continue; }
                        }
                    }
                }
                else
                {
                    throw new Exception(string.Format("SFTP文件下载失败，原因：{0}", "SFTP未连接"));
                }
                ;
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
            }
        }
      
        #endregion

        #region 移动SFTP文件
        /// <summary>
        /// 移动SFTP文件
        /// </summary>
        /// <param name="oldRemotePath">旧远程路径</param>
        /// <param name="newRemotePath">新远程路径</param>
        public void Move(string oldRemotePath, string newRemotePath)
        {
            try
            {
                Connect();
                sftp.RenameFile(oldRemotePath, newRemotePath);
                Disconnect();
            }
            catch (Exception ex)
            {
                // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件移动失败，原因：{0}", ex.Message));
                throw new Exception(string.Format("SFTP文件移动失败，原因：{0}", ex.Message));
            }
        }
        #endregion

    }
    
    //public class SFTPHelper
    //{

    //    private Session m_session;
    //    private Channel m_channel;
    //    private ChannelSftp m_sftp;
    //    private static readonly string defRemotePath = "/";//默认操作是都是从根目录开始
    //    //host:sftp地址   user：用户名   pwd：密码        
    //    public SFTPHelper(string host, string user, string pwd)
    //    {
    //        string[] arr = host.Split(':');
    //        string ip = arr[0];
    //        int port = 22;
    //        if (arr.Length > 1)
    //            port = Int32.Parse(arr[1]);
    //        JSch jsch = new JSch();
    //        m_session = jsch.getSession(user, ip, port);
    //        MyUserInfo ui = new MyUserInfo();
    //        ui.setPassword(pwd);
    //        m_session.setUserInfo(ui);
    //    }

    //    //SFTP连接状态        
    //    public bool Connected { get { return m_session.isConnected(); } }

    //    //连接SFTP        
    //    public bool Connect()
    //    {
    //        try
    //        {
    //            if (!Connected)
    //            {
    //                m_session.connect(30000);
    //                m_channel = m_session.openChannel("sftp");
    //                m_channel.connect();
    //                m_sftp = (ChannelSftp)m_channel;
    //            }
    //            return true;
    //        }
    //        catch (Exception ex)
    //        {
    //            Tools.LogCls.WriteLog(string.Format("连接SFTP失败，原因：{0}", ex.Message));
    //            return false;
    //            //throw new Exception(string.Format("连接SFTP失败，原因：{0}", ex.Message));
    //        }
    //    }

    //    //断开SFTP        
    //    public void Disconnect()
    //    {
    //        if (Connected)
    //        {
    //            m_channel.disconnect();
    //            m_session.disconnect();
    //        }
    //    }

    //    //SFTP存放文件        
    //    public void Put(string localPath, string remotePath)
    //    {
    //        Tamir.SharpSsh.java.String oldPath = "";
    //        Tamir.SharpSsh.java.String newPath = "";
    //        try
    //        {

    //            if (Connected)
    //            {
    //                Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
    //                Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
    //                //H:\sftp\BizMsg.rar.temp.temp
    //                m_sftp.put(src, dst);
    //                FileInfo file = new FileInfo(localPath);
    //                oldPath = new Tamir.SharpSsh.java.String(remotePath + "/" + file.Name);
    //                newPath = new Tamir.SharpSsh.java.String(remotePath + "/" + file.Name.Replace(".temp", ""));
                    
    //                m_sftp.rename(oldPath, newPath);

    //            }
    //            else
    //            {
    //                Connect();
    //            }
    //        }
    //        catch (Exception ex)
    //        {
    //            m_sftp.rm(oldPath);
    //            throw new Exception(string.Format("上传文件失败，原因：{0}", ex.Message));
    //        }

    //    }

    //    //SFTP获取文件        
    //    public bool Get(string remotePath, string localPath)
    //    {
    //        try
    //        {
    //            Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
    //            Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
    //            m_sftp.get(src, dst);
    //            return true;
    //        }
    //        catch (Exception ex)
    //        {
    //            Tools.LogCls.WriteLog(string.Format("连接SFTP失败，原因：{0}", ex.Message));
    //            return false;
    //        }
    //    }
    //    //删除SFTP文件
    //    public bool Delete(string remoteFile)
    //    {
    //        try
    //        {
    //            m_sftp.rm(remoteFile);
    //            return true;
    //        }
    //        catch(Exception ex)
    //        {
    //            Tools.LogCls.WriteLog(string.Format("连接SFTP失败，原因：{0}", ex.Message));
    //            return false;
    //        }
    //    }

    //    //获取SFTP文件列表        
    //    public ArrayList GetFileList(string remotePath, string fileType)
    //    {
    //        try
    //        {
    //            ArrayList objList = new ArrayList();
    //            Tamir.SharpSsh.java.String rPath = new Tamir.SharpSsh.java.String(remotePath);
    //            string fullRemotePath = defRemotePath + remotePath.TrimStart('/');
    //            if (DirExist(fullRemotePath))
    //            {
    //                Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(rPath);
    //                foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
    //                {
    //                    string sss = qqq.getFilename();
    //                    Regex r = new Regex(fileType);
    //                    Match m = r.Match(sss);
    //                    if (m.Success)
    //                    { objList.Add(sss); }
    //                    else { continue; }
    //                }
    //            }
    //            else
    //            {
    //                Tools.LogCls.WriteLog("远程路径不存在,请确定SFTP服务器是否存在该路径。");
    //            }
    //            return objList;
    //        }
    //        catch (Exception ex)
    //        {
    //            Tools.LogCls.WriteLog("获取反馈报文异常：" + ex.Message);
    //            return null;
    //        }
    //    }

    //    /// <summary>
    //    /// 目录是否存在
    //    /// </summary>
    //    /// <param name="dirName">目录名称必须从根开始</param>
    //    /// <returns></returns>
    //    public bool DirExist(string dirName)
    //    {
    //        try
    //        {
    //            m_sftp.ls(defRemotePath + dirName.TrimStart('/'));
    //            return true;
    //        }
    //        catch (Tamir.SharpSsh.jsch.SftpException ex)
    //        {
    //            Tools.LogCls.WriteLog(string.Format("连接SFTP失败，原因：{0}", ex.Message));
    //            return false;
    //        }
    //    }
    //    //登录验证信息        
    //    public class MyUserInfo : UserInfo
    //    {
    //        String passwd;
    //        public String getPassword() { return passwd; }
    //        public void setPassword(String passwd) { this.passwd = passwd; }

    //        public String getPassphrase() { return null; }
    //        public bool promptPassphrase(String message) { return true; }

    //        public bool promptPassword(String message) { return true; }
    //        public bool promptYesNo(String message) { return true; }
    //        public void showMessage(String message) { }
    //    }
    //}

    public class FtpHelper
    {
        public static readonly FtpHelper Instance = new FtpHelper();

        /// <summary>  
        /// 取得文件名  
        /// </summary>  
        /// <param name="ftpPath">ftp路径</param>  
        /// <returns></returns>  
        public string[] GetFilePath(string userId, string pwd, string ftpPath)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                //reqFTP.UsePassive = false;
                reqFTP.UsePassive = true;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf('\n'), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception ex)
            {
                downloadFiles = null;
                return downloadFiles;
            }
        }

        //ftp的上传功能  
        public void Upload1(string userId, string pwd, string filename, string ftpPath)
        {
            FtpWebRequest reqFTP;
            FileInfo fileInf = new FileInfo(filename);
            // 根据uri创建FtpWebRequest对象   
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileInf.Name + ".temp"));
            try
            {
          
              
                // ftp用户名和密码  
                reqFTP.Credentials = new NetworkCredential(userId, pwd);

                reqFTP.UsePassive = true;
                // 默认为true，连接不会被关闭  
                // 在一个命令之后被执行  
                reqFTP.KeepAlive = false;
                // 指定执行什么命令  
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 指定数据传输类型  
                reqFTP.UseBinary = true;
                // 上传文件时通知服务器文件的大小  
                reqFTP.ContentLength = fileInf.Length;
                // 缓冲大小设置为2kb  
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                // 打开一个文件流 (System.IO.FileStream) 去读上传的文件  
                FileStream fs = fileInf.OpenRead();

                // 把上传的文件写入流  
                Stream strm = reqFTP.GetRequestStream();
                // 每次读文件流的2kb  
                contentLen = fs.Read(buff, 0, buffLength);
                // 流内容没有结束  
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream  
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流  
                strm.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                throw;
            }
            finally
            {
                reqFTP.RenameTo = fileInf.Name;
            }


        }
        public void Upload(string userId, string pwd, string filename, string ftpPath)
        {
            FtpWebRequest reqFTP;
            FileInfo fileInf = new FileInfo(filename);
            // 根据uri创建FtpWebRequest对象   
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileInf.Name + ".temp"));
            // ftp用户名和密码  
            reqFTP.Credentials = new NetworkCredential(userId, pwd);

            reqFTP.UsePassive = true;
            // 默认为true，连接不会被关闭  
            // 在一个命令之后被执行  
            reqFTP.KeepAlive = false;
            // 指定执行什么命令  
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 指定数据传输类型  
            reqFTP.UseBinary = true;
            // 上传文件时通知服务器文件的大小  
            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为2kb  
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件  
            FileStream fs = fileInf.OpenRead();

            // 把上传的文件写入流  
            Stream strm = reqFTP.GetRequestStream();
            // 每次读文件流的2kb  
            contentLen = fs.Read(buff, 0, buffLength);
            try
            {
                // 流内容没有结束  
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream  
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                // 关闭两个流  
            }
            catch
            {
                throw;
            }
            finally
            {
                strm.Close();
                fs.Close();
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileInf.Name + ".temp"));
                reqFTP.Credentials = new NetworkCredential(userId, pwd);
                reqFTP.UseBinary = true;
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = fileInf.Name;
                FtpWebResponse ftpWebResponse = (FtpWebResponse)reqFTP.GetResponse();
                ftpWebResponse.Close();
            }


        }
   
        public void Delete(string userId, string pwd, string ftpPath, string fileName)
        {
            FtpWebRequest reqFTP;

            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(userId, pwd);
            reqFTP.UsePassive = true;
            FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse();
            string sStatus = listResponse.StatusDescription;

        }

        //从ftp服务器上下载文件的功能  
        public void Download(string userId, string pwd, string ftpPath, string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(userId, pwd);
            reqFTP.UsePassive = true;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();


        }


        //从ftp服务器上下载文件的功能  
        public void DownloadAddGUID(string userId, string pwd, string ftpPath, string filePath, string fileName)
        {
            FtpWebRequest reqFTP;
            string rq = Guid.NewGuid().ToString();
            FileStream outputStream = new FileStream(filePath + "\\" + rq + fileName, FileMode.Create);
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(userId, pwd);
            reqFTP.UsePassive = true;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                outputStream.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            outputStream.Close();
            response.Close();


        }

    }
}
